# -*- coding: utf-8 -*-
__author__ = 'BuddyHolly'

import os


# =================
# *** 图片存储类 ***
# =================

class CurPic:

    # 初始化需要传入pptx的Presentation对象，图片信息[slideid，shapeid]，存储路径
    def __init__(self, prs, info, save_path):
        self.slide_id = info[0]
        self.shape_id = info[1]
        self.slide = prs.slides[self.slide_id]
        self.shape = self.slide.shapes[self.shape_id]
        self.save_path = save_path
        self.file_name = ''

    def get_pic(self):
        # ===============================================
        # 从当前shape中获取图片信息
        # pptx自建类shape中提取保护信息_blob（图像流信息）！！！
        # ===============================================
        img_pic = self.shape._pic
        img_rid = img_pic.xpath('./p:blipFill/a:blip/@r:embed')[0]
        img_part = self.slide.part.related_parts[img_rid]
        img_data = img_part._blob
        img_type = img_part.content_type

        # 文件名格式 : slideid_shapeid.jpg/png
        filename = ''
        # 通过content_type判断文件类型
        if 'image/jpeg' in img_type:
            filename = str(self.slide_id) + '_' + str(self.shape_id) + '.jpg'

        elif 'image/png' in img_type:
            filename = str(self.slide_id) + '_' + str(self.shape_id) + '.png'

        # 存储图片
        tem_path = os.path.join(self.save_path, filename)
        with open(tem_path, 'wb+') as file:
            file.write(img_data)
            self.file_name = filename
